package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IFollowService followService;


    @Override
    public Result queryBlogofFollow(Long lastId, Integer offset) {
        Long userId = UserHolder.getUser().getId();
        Set<ZSetOperations.TypedTuple<String>> tupleSet = stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(RedisConstants.FEED_KEY + userId,  0,lastId, offset, 3);
        if (tupleSet == null || tupleSet.isEmpty()) {
            return Result.ok();
        }
        List<Long> ids = new ArrayList<>(tupleSet.size());
        long minTime = 0;
        int count = 1 ;
        for (ZSetOperations.TypedTuple<String> tuple : tupleSet) {
            String id = tuple.getValue();
            ids.add(Long.valueOf(id));
            if(minTime == tuple.getScore().longValue()){
                count++;
            }else{
                minTime = tuple.getScore().longValue();
                count = 1;
            }
        }
        String join = StrUtil.join(",", ids);
        List<Blog> list = query().in("id",ids).last("ORDER BY FIELD(id ,"+join+")").list();

        for(Blog blog: list){
            Long blogUserId = blog.getUserId();
            User user = userService.getById(blogUserId);
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
            if(UserHolder.getUser()!=null){
                Double score = stringRedisTemplate.opsForZSet().score(RedisConstants.BLOG_LIKED_KEY + blog.getId(), blogUserId.toString());
                if (score != null) {
                    blog.setIsLike(true);
                }
            }
        }
        //TODO:offset获取有误
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(list);
        scrollResult.setOffset(count);
        scrollResult.setMinTime(minTime);
        return Result.ok(scrollResult);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        save(blog);
        List<Follow> list = followService.query().eq("follow_user_id", user.getId()).list();
        List<Long> fanList = list.stream().map(Follow::getUserId).collect(Collectors.toList());
        for (Long id : fanList){
            stringRedisTemplate
                    .opsForZSet()
                    .add(RedisConstants.FEED_KEY+id,blog.getId().toString(), System.currentTimeMillis());

        }
        // 返回id
        return Result.ok(blog.getId());
    }

    @Override
    public Result getHotBlogs(Integer current) {
        // 根据用户查询
        Page<Blog> page = this.query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        for(Blog blog: records){
            Long userId = blog.getUserId();
            User user = userService.getById(userId);
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
            if(UserHolder.getUser()!=null){
                Double score = stringRedisTemplate.opsForZSet().score(RedisConstants.BLOG_LIKED_KEY + blog.getId(), userId.toString());
                if (score != null) {
                    blog.setIsLike(true);
                }
            }
        }
        return Result.ok(records);
    }

    @Override
    public Result getDetailById(Long id) {
        // 根据用户查询
        Blog blog = this.getById(id);
        if (blog == null) {
            return Result.fail("blog不存在");
        }
        // 查询用户
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());

        if(UserHolder.getUser()!=null){
            Double score = stringRedisTemplate.opsForZSet().score(RedisConstants.BLOG_LIKED_KEY + id, userId.toString());
            if (score != null) {
                blog.setIsLike(true);
            }
        }
        return Result.ok(blog);
    }

    @Override
    public Result likeBlog(Long id) {
        String userId = UserHolder.getUser().getId().toString();
        Double score = stringRedisTemplate.opsForZSet().score(RedisConstants.BLOG_LIKED_KEY + id, userId.toString());
        if (score == null) {
            boolean updated = update().setSql("liked = liked + 1").eq("id", id).update();
            if (updated) {
                stringRedisTemplate.opsForZSet().add(RedisConstants.BLOG_LIKED_KEY + id,userId,System.currentTimeMillis());
                return Result.ok();
            }
            return Result.fail("点赞失败");
        }
        boolean updated = update().setSql("liked = liked - 1").eq("id", id).update();
        if (updated) {
            stringRedisTemplate.opsForZSet().remove(RedisConstants.BLOG_LIKED_KEY + id,userId);
            return Result.ok();
        }
        return Result.fail("取消点赞失败");
        //TODO:前端高亮
    }

    @Override
    public Result queryBlogLikes(Long id) {
        Set<String> range = stringRedisTemplate.opsForZSet().range(RedisConstants.BLOG_LIKED_KEY + id, 0, 4);
        if(range == null || range.isEmpty() ){
            return Result.ok(Collections.emptyList());
        }
        List<Long> userIds = range.stream().map(Long::valueOf).collect(Collectors.toList());
        String join = StrUtil.join(",", userIds);
        List<UserDTO> list = userService.query()
                .in("id",userIds).last("ORDER BY FIELD(id ,"+join+")").list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(list);
    }
}
